﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ServiceClient;
using WebMvc.Dao;
using WebMvc.Models;

namespace WebMvc.Controllers
{
    [HandleError]
    public class TicketsController : Controller
    {
        private readonly TicketDao _ticketDao;
        private readonly SalaDao _salaDao;
        private readonly OpenMeetingsServiceClient _serviceClient;

        public TicketsController(TicketDao ticketDao, SalaDao salaDao, OpenMeetingsServiceClient serviceClient)
        {
            if (ticketDao == null)
                throw new ArgumentNullException("ticketDao");

            if (salaDao == null)
                throw new ArgumentNullException("salaDao");

            if (serviceClient == null)
                throw new ArgumentNullException("serviceClient");

            _ticketDao = ticketDao;
            _salaDao = salaDao;
            _serviceClient = serviceClient;
        }

        // GET: /Tickets/
        public ActionResult Index()
        {
            var result = _ticketDao.GetAll().ToList();

            var roomIds = new List<int>();

            foreach (var ticket in result)
            {
                if (!ticket.IdSala.HasValue)
                    continue;

                // Obtengo la sala
                ticket.Sala = _salaDao.GetById(ticket.IdSala.Value);

                if (ticket.Sala.IdOpenMeetings.HasValue)
                    roomIds.Add(ticket.Sala.IdOpenMeetings.Value);
            }

            // Cargo la cantidad de usuarios en cada sala
            foreach (var roomUsrs in _serviceClient.GetActiveUsers(roomIds.ToArray()))
            {
                var roomId = roomUsrs.Key;
                var ticket =
                    result.First(
                        t =>
                            t.IdSala.HasValue && t.Sala.IdOpenMeetings.HasValue && t.Sala.IdOpenMeetings.Value == roomId);

                ticket.UsuariosActivosEnSala = roomUsrs.Value;
            }
            

            return View(result);
        }

        // GET: /Tickets/Ver/5
        public ActionResult Ver(int id)
        {
            var result = _ticketDao.GetById(id);

            if (result.IdSala.HasValue)
            {
                result.Sala = _salaDao.GetById(result.IdSala.Value);

                if (result.Sala.IdOpenMeetings.HasValue)
                    result.UsuariosActivosEnSala = _serviceClient.GetActiveUsers(result.Sala.IdOpenMeetings.Value);
            }

            return View(result);
        }

        // GET: /Tickets/Crear
        public ActionResult Crear()
        {
            return View();
        } 

        // POST: /Tickets/Create
        [HttpPost]
        public ActionResult Crear(Ticket ticket)
        {
            
            if (Request.Form["crearSalaAutomaticamente"].Contains("true"))
            {
                // Creo la sala con parámetros predefinidos
                var sala = new Sala
                {
                    Nombre = ticket.Nombre,
                    Comentario = ticket.Descripcion,
                    CantidadParticipantes = 10,
                    EsPublica = true,
                    ParaCitarse = true,
                    ParaDemo = false,
                    DuracionDemo = 0,
                    SalaModerada = false,
                    Tipo = TipoSala.Conferencia,
                    TipoExterno = "Probando"
                };

                // Creo la sala
                _salaDao.Create(sala);

                // Obtengo el id y lo actualizo en los objetos
                var idAsignado = _salaDao.GetByNombre(sala.Nombre).Id;
                sala.Id = idAsignado;
                ticket.IdSala = idAsignado;

                // Creo la sala en OM
                _serviceClient.CreateNewRoom(sala);

                // Obtengo el Id de la sala.
                var idOpenMeetings = _serviceClient.GetRoomId(sala);

                // Actualizo la sala con el Id de OpenMeetings
                sala.IdOpenMeetings = Convert.ToInt32(idOpenMeetings);
                _salaDao.Update(sala);
            }

            ticket.FechaInicio = DateTime.Now;

            _ticketDao.Create(ticket);
            return RedirectToAction("Index");
        }
        
        // GET: /Tickets/Edit/5
        public ActionResult Editar(int id)
        {
            return View();
        }

        //
        // POST: /Tickets/Edit/5

        [HttpPost]
        public ActionResult Editar(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: /Tickets/Delete/5
        public ActionResult Eliminar(int id)
        {
            var ticket = _ticketDao.GetById(id);

            _ticketDao.Delete(id);

            if (ticket.IdSala.HasValue)
                _salaDao.Delete(ticket.IdSala.Value);
            
            return RedirectToAction("Index");
        }

        // GET: /Tickets/Cerrar/5
        public ActionResult Cerrar(int id)
        {
            var ticket = _ticketDao.GetById(id);
            ticket.FechaFin = DateTime.Now;

            _ticketDao.Update(ticket);

            return RedirectToAction("Index");
        }
    }
}
